/**
 * 采集方案表格
 */

import * as React from "react";
import { Component } from "react";
import {
  Row,
  Col,
  Button,
  Modal,
  Spin,
  Table,
  Space,
  Typography,
  Input,
  Select,
  Form,
  Radio,
  Switch,
} from "antd";
import moment from "moment";
import { PlusOutlined } from "@ant-design/icons";
import { observable } from "mobx";
import { observer } from "mobx-react";
import IconFont from "../../../../../../assets/ICON";
import {
  AjaxData,
  columnsDataCLass,
} from "../../../../../../data/interface/publicInterface";
import { ergodicListAddIdToKey } from "../../../../../../utils/common";
import {
  getCollectionMethodList,
  addCollectionMethod,
  deleteCollectionMethod,
  updateCollectionMethod,
  getProtocalType,
  enableAmi,
} from "../../../ServeApi/index";
import FeedModelBind from "../FeedModelBind";
import CollectionMethodSetting from "../CollectionMethodSetting";
import "./index.less";

const { Text } = Typography;
const { Option } = Select;

export interface LineLossTableProps {}

export interface LineLossTableState {
  loading: boolean;
}
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};

export interface CollectionMethodTableProps {}

export interface CollectionMethodTableState {}
@observer
class CollectionMethodTable extends Component<
  CollectionMethodTableProps,
  CollectionMethodTableState
> {
  private Mod: string = "add";
  private isModalVisible: boolean = false;
  private instance: any | null = null;
  private initValue: any | null = null;
  private pageIndex: number = 1;
  private pageSize: number = 20;
  private total: number = 0;

  private dataSouce: any[] = [];
  @observable dataBindSouce: any[] = [];
  private ProtocalType: any[] = []; //协议集合
  private isFeedModalVisible: boolean = false;
  private isSettingModalVisible: boolean = false;
  bound: number = 1;

  @observable
  private columns: columnsDataCLass[] = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "协议类型",
      dataIndex: "protocalTypeName",
      key: "protocalTypeName",
    },
    {
      title: "使用类型",
      dataIndex: "type",
      key: "type",
      render: (text) => {
        let str = "";
        switch (text) {
          case "0":
            str = "通用";
            break;
          case "1":
            str = "专用";
            break;
          default:
            str = "暂无";
            break;
        }
        return str;
      },
    },
    {
      title: "绑定设备",
      dataIndex: "type",
      key: "type",
      render: (text, record) => {
        if (text === "1") {
          return (
            <span
              style={{ cursor: "pointer" }}
              onClick={() => {
                this.onFeed(record);
              }}
            >
              <IconFont
                type="icon_form_bangding"
                style={{ color: "#1890FF" }}
              />
              <Text>绑定设备</Text>
            </span>
          );
        } else {
          return "无效";
        }
      },
    },
    {
      title: "是否启用",
      dataIndex: "isEnable",
      key: "isEnable",
      render: (text, record) => {
        let b: boolean = text === "0" ? true : false;
        return (
          <Switch
            checked={b}
            onChange={(checked) => {
              this.onChangeEnable(checked, record);
            }}
          />
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (text: string | null) => {
        if (text) {
          return moment(text).format("YYYY-MM-DD");
        } else {
          return "暂无";
        }
      },
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  //   this.Meth = "out";
                  //   this.onFeed(record);
                  this.onSetting(record);
                }}
              >
                <IconFont
                  type="icon_form_peizhi"
                  style={{ color: "#1890FF" }}
                />
                <Text>配置</Text>
              </span>
              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.Mod = "updata";
                  this.onEdit(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>

              <span
                style={{ cursor: "pointer" }}
                onClick={() => {
                  this.onDelete(record);
                }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
                <Text>删除</Text>
              </span>
            </Space>
          </>
        );
      },
    },
  ];
  state = { loading: false };
  render() {
    return (
      <div className="CollectionMethodTable">
        <div className="rowcon_body">
          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                this.Mod = "add";
                this.addMenuModal();
              }}
            >
              新增
            </Button>
          </div>
          <div className="rowcon_bottom"></div>
          <Spin spinning={this.state.loading}>
            <Table
              columns={this.columns}
              dataSource={this.dataSouce}
              pagination={{
                pageSize: this.pageSize,
                total: this.total,
                current: this.pageIndex,
                onChange: (page: number) => {
                  this.pageIndex = page;
                  // this.getPream();
                },
              }}
            ></Table>
          </Spin>
          <Modal
            title={this.Mod === "add" ? "新增采集方案" : "编辑采集方案"}
            visible={this.isModalVisible}
            onOk={() => {
              this.handleOk();
            }}
            onCancel={() => {
              this.handleCancel();
            }}
          >
            <Form {...formItemLayout} ref={(el) => (this.instance = el)}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label="名称："
                    name="name"
                    rules={[
                      {
                        required: true,
                        message: "采集方案名称必填",
                      },
                    ]}
                  >
                    <Input placeholder="请填写采集方案名称" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="协议"
                    name="protocalTypeId"
                    rules={[
                      {
                        required: true,
                        message: "协议类型必填",
                      },
                    ]}
                  >
                    <Select placeholder="请选择协议类型">
                      {this.ProtocalType.map((item: any, index: number) => {
                        return (
                          <Option value={item.id} key={index}>
                            {item.name}
                          </Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="类型："
                    name="type"
                    rules={[
                      {
                        required: true,
                        message: "方案类型必填",
                      },
                    ]}
                  >
                    <Radio.Group>
                      <Radio value="0">通用</Radio>
                      <Radio value="1">专用</Radio>
                    </Radio.Group>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
          {/**
           * 绑定设备
           * 采集方案Id
           * 是否加载isFeedModalVisible
           */}
          {this.isFeedModalVisible && this.initValue ? (
            <FeedModelBind
              isFeedModalVisible={this.isFeedModalVisible}
              record={this.initValue ? this.initValue : null}
              key={this.initValue["id"]}
              onCancel={() => {
                this.handleFeedCancel();
              }}
            />
          ) : null}

          {/**
           * 配置命令
           */}
          {this.isSettingModalVisible && this.initValue ? (
            <CollectionMethodSetting
              isModalVisible={this.isSettingModalVisible}
              record={this.initValue ? this.initValue : null}
              key={this.initValue["id"]}
              onCancel={() => {
                this.handleSettingCancel();
              }}
            />
          ) : null}
        </div>
      </div>
    );
  }
  componentWillMount() {
    this.init();
  }
  //初始化
  init() {
    this.getProtocalType();
    this.getListByPage();
  }

  /** 主动操作*/
  //选中的设备
  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };
  //绑定设备
  onFeed(item: any) {
    this.initValue = item;
    // this.getPream(); //更新请求
    this.ifFeedVisible();
  }
  //供出设备绑定弹窗取消
  handleFeedCancel() {
    this.initValue = null;
    this.ifFeedVisible();
    // this.clearFeedModel();
  }
  handleSettingCancel() {
    this.initValue = null;
    this.ifSettingVisible();
  }
  //绑定，未绑定切换
  changeBound(bound: number) {
    this.bound = bound;
    // this.ResetPaging();
    // this.getPream(); //更新请求
    this.forceUpdate();
  }
  ifFeedVisible() {
    this.isFeedModalVisible = !this.isFeedModalVisible;
    this.forceUpdate();
  }
  ifSettingVisible() {
    this.isSettingModalVisible = !this.isSettingModalVisible;
    this.forceUpdate();
  }
  //是否启用
  onChangeEnable(check, record) {
    let pream = {
      enable: check,
      amiId: record["id"],
    };
    this.isenableAmi(pream);
  }
  //设置
  onSetting(item) {
    console.log(item);
    this.initValue = item;
    this.ifSettingVisible();
  }
  //编辑采集方案
  onEdit(item) {
    this.initValue = item;
    this.ifVisible();
    setTimeout(() => {
      if (this.instance) {
        const container: any = (this.instance as any) as HTMLDivElement;
        container.setFieldsValue(item);
      }
    });
  }
  //删除采集方案触发
  onDelete(item) {
    let pream = {
      amiId: item.id,
    };
    let _this = this;
    Modal.confirm({
      title: "是否确认删除采集方案",
      onOk: () => {
        _this.DeleteCollectionMethod(pream);
      },
    });
  }
  //新增菜单对话框
  addMenuModal() {
    this.ifVisible();
  }
  //采集方案弹窗取消
  handleCancel() {
    this.ifVisible();
    this.clearFromData();
  }
  handleOk() {
    let _this = this;
    const container: any = (this.instance as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        _this.setDataSoucePream(res);
        _this.ifVisible();
        _this.clearFromData();
      })
      .catch((err) => {
        console.log(err);
      });
  }
  /**方法调用 */
  //主表新增编辑开关
  ifVisible() {
    this.isModalVisible = !this.isModalVisible;
    this.forceUpdate();
  }
  //通过id获取list的name
  getIdForInName(list: any[], id: string) {
    let name = "";
    list.map((item) => {
      if (item["id"] === id) {
        name = item["name"];
      }
      return item;
    });
    return name;
  }
  //参数处理与新增，编辑函数的参数
  setDataSoucePream(item: any) {
    switch (this.Mod) {
      case "add":
        item.protocalTypeName = this.getIdForInName(
          this.ProtocalType,
          item["protocalTypeId"]
        );
        item.isEnable = "0"; //默认为可用
        this.AddCollectionMethod(item);

        break;
      case "updata":
        item["id"] = this.initValue["id"];
        item["isEnable"] = this.initValue["isEnable"];
        item.protocalTypeName = this.getIdForInName(
          this.ProtocalType,
          item["protocalTypeId"]
        );
        this.UpdateCollectionMethod(item);
        break;
      default:
        break;
    }
  }
  //清空采集方案对象From表单
  clearFromData() {
    this.initValue = null;
    if (this.instance) {
      const container: any = (this.instance as any) as HTMLDivElement;
      container.setFieldsValue({
        name: undefined,
        protocalTypeId: undefined,
        type: undefined,
      });
    }
  }
  /**数据请求 */
  //获取采集方案列表分页请求
  async getListByPage() {
    let _this = this;
    this.setState({ loading: true });
    let pream = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      queryData: null,
    };
    try {
      let res: any = await getCollectionMethodList(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.dataSouce = json.data.records;
        _this.total = json.data.total;
        _this.setState({ loading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //获取协议集合
  async getProtocalType() {
    let _this = this;
    try {
      let res: any = await getProtocalType().catch((err) => {
        console.log(err);
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.ProtocalType = ergodicListAddIdToKey(json.data);
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //新增采集方案
  async AddCollectionMethod(item) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await addCollectionMethod(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //删除采集方案
  async DeleteCollectionMethod(item) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await deleteCollectionMethod(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //编辑采集方案
  async UpdateCollectionMethod(item) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await updateCollectionMethod(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //更新采集方案状态（是否启用状态）
  async isenableAmi(item) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await enableAmi(JSON.stringify(item)).catch((err) => {
        console.log(err);
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
}

export default CollectionMethodTable;
